# -*- encoding=UTF-8 -*-
__author__ = "zichuanlu"

import os
import subprocess
import sys
import time
import unittest

sys.path.append(os.path.realpath('../'))

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from poco.exceptions import PocoException

import common
from common.otherUtl import myTool
from airtest.core.api import init_device, start_app, stop_app, snapshot, sleep
from airtest.core.helper import log


class Moniter(unittest.TestCase):

    def setUp(self):
        """
        获取udid，设置日志路径，截图路径等一系列前置操作
        :param
        :return:
        """
        self.poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
        self.uuid = self.poco.device.uuid

        self.package_name = "com.heytap.smarthome"
        self.runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self.setPath(abs_path=os.path.dirname(os.path.abspath(__file__)))

        init_device("Android", self.uuid)

        stop_app(self.package_name)
        start_app(self.package_name)

        self.count = 1

    @common.otherUtl.myTool.repeat(times=1000)
    def testLink(self):
        start_app(self.package_name)
        time.sleep(5)

        end_time = None
        start_time = None
        is_success = False
        is_error = False

        try:
            # 1、点击播放
            self.poco("com.heytap.smarthome:id/ll_item").wait().click()
            start_time = time.time()

            # 识别是否出图

            for i in range(300):
                # call_btn = self.poco("com.heytap.camera.gwell:id/btn_select_call")
                # if call_btn.exists() is True:
                #     call_btn_clickable = call_btn.attr("touchable")
                #     if call_btn_clickable is True:
                #         end_time = time.time()
                #         is_success = True
                #         break
                speed_text = self.poco("com.heytap.camera.gwell:id/tv_video_panel_net_speed")
                if speed_text.exists():
                    speed = speed_text.attr("text")
                    if speed is not None:
                        if int(str(speed).replace(" KB/s", "")) > 0:
                            end_time = time.time()
                            is_success = True
                            break
                    # if enable is True:
                    #     end_time = time.time()
                    #     is_success = True
                    #     break
                else:
                    time.sleep(0.01)

        except PocoException as e:
            log(e)
            is_error = True
        finally:
            dt = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
            if is_success is True:
                myTool.write_excel_xls_append(filepath=self.report_file_path,
                                              data=[dt, self.count, str("%.2f" % (end_time - start_time))])
            else:
                if is_error is False:
                    # 定位出错才截图和记入失败
                    myTool.write_excel_xls_append(filepath=self.report_file_path,
                                                  data=[dt, self.count, "监控失败 或 超时"])

                    snapshot(self.fail_pic + dt + ".png")
        if is_error is False:
            self.count += 1
        sleep(5)

        stop_app(self.package_name)
        sleep(5)

    def tearDown(self):
        stop_app(self.package_name)
        self.poco.stop_running()

    def setPath(self, abs_path):
        """
        设置日志等路径
        :param
        :return:
        """
        dt = time.strftime("%Y-%m-%d", time.localtime())

        self.fail_pic = abs_path + "/fail_pic/" + dt + "/" + self.uuid + "/"
        self.report_dir = abs_path + "/report/" + dt + "/" + self.uuid + "/"
        self.report_file_path = self.report_dir + self.runtime + ".xlsx"

        if not os.path.exists(self.report_dir):
            os.makedirs(self.report_dir)
        if not os.path.exists(self.fail_pic):
            os.makedirs(self.fail_pic)
        if not os.path.exists(self.report_file_path):
            # 创建文件并写入标题
            myTool.create_xlsx(self.report_file_path)
            myTool.write_excel_xls_append(filepath=self.report_file_path, data="")


if __name__ == '__main__':
    unittest.main()
